package com.xinyue.gateway.server.handler;

import com.xinyue.gateway.server.MessageID;
import com.xinyue.gateway.server.message.GateMessageHeader;
import com.xinyue.gateway.server.message.GateMessagePackage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * 
 * @ClassName: ChannelHeartbeatHandler
 * @Description: 负责管理连接的心跳，如果客户端长时间没给服务器发送消息，服务器将主动断开连接
 * @author: wgs
 * @date: 2018年12月3日 上午3:21:49
 */

public class GameIdleStateHandler extends IdleStateHandler {
    
  
    public GameIdleStateHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
        super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
    }

  

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof GateMessagePackage) {
            GateMessagePackage gateMessagePackage = (GateMessagePackage) msg;
            GateMessageHeader messageHeader = gateMessagePackage.getHeader();
            //如果是心跳消息，则不参与writeidel的统计，如果长时间只有心跳消息，那么连接需要断开
            if(messageHeader.getMessageId() == MessageID.HeartbeatMessageId) {
                //返回心跳消息
                ctx.writeAndFlush(gateMessagePackage);
            } else {
                super.write(ctx, msg, promise);
            }
        } 
       
    }
}
